package com.example.demo.controller;

import com.example.demo.config.DatabaseProperties;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
public class HelloWorldController {

    @Resource
    private DatabaseProperties dbProperties;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private UserService userService;

    @GetMapping(value = "/hello")
    public String index(
            @RequestParam(value = "name", required = false, defaultValue = "yfh") String name,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "size", required = false, defaultValue = "1") Integer size
    ) {

        return name + "--" + page.toString() + "--" + size.toString();

//        return this.ls1();
//        return this.ls2();
//        return this.ls3(name);
//        return this.ls4(page, size);
    }

    private String ls1() {
        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql, (resultSet, i) -> {
            User user = new User();
            user.setId(resultSet.getInt("id"));
            user.setName(resultSet.getString("name"));
            user.setGender(resultSet.getInt("gender"));
            user.setCreatedAt(resultSet.getDate("created_at"));
            return user;
        });

        StringBuilder output = new StringBuilder();
        for (User u : users) {
            output.append(u.toString()).append("\n");
        }

        return output.toString();
    }

    private String ls2() {
        String sql = "select * from user";
        return jdbcTemplate.queryForList(sql).toString();
    }

    private User ls3(String name) {
        return userService.getUserByName(name);
    }

    private Page<User> ls4(Integer page, Integer size) {
        return userService.getUserList(page, size);
    }
}
